package controllers

import (
	"github.com/Unknwon/com"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"go.demo/unknown/go-web/beego/beeblog/models"
	"os"
	"path"
	"strconv"
	"strings"
)

type TopicController struct {
	beego.Controller
}

func (this *TopicController) Delete() {
	if err := models.DeleteTopic(this.Ctx.Input.Param("0")); err != nil {
		logs.Error(err)
	}
	this.Redirect("/topic", 302)
}

func (this *TopicController) Modify() {
	this.TplName = "topic_modify.html"
	if topic, err := models.GetTopic(this.Ctx.Input.Param("0")); err != nil {
		logs.Error(err)
	} else {
		this.Data["Topic"] = topic
	}
}
func (this *TopicController) Add() {
	this.TplName = "topic_add.html"
}
func (this *TopicController) View() {
	this.TplName = "topic_view.html"
	this.Data["IsTopic"] = true
	this.Data["IsLogin"] = checkAccount(this.Ctx)
	tid := this.Ctx.Input.Param("0")
	if topic, err := models.GetTopic(tid); err != nil {
		logs.Error(err)
		this.Redirect("/", 302)
		return
	} else {
		if err := models.UpdateTopic(tid, 1, 0); err != nil {
			logs.Error(err)
		}
		this.Data["Topic"] = topic
		this.Data["Labels"] = strings.Split(topic.Labels, " ")
	}

	if replies, err := models.GetAllReplies(tid); err != nil {
		logs.Error(err)
		this.Redirect("/", 302)
	} else {
		this.Data["Replies"] = replies
		this.Data["IsLogin"] = checkAccount(this.Ctx)
	}
}
func (this *TopicController) Post() {
	if !checkAccount(this.Ctx) {
		this.Redirect("/login", 302)
		return
	}

	tid := this.Input().Get("tid")
	title := this.Input().Get("title")
	content := this.Input().Get("content")
	category := this.Input().Get("category")
	labels := this.Input().Get("labels")
	var attachment string
	if _, fh, err := this.GetFile("attachment"); err != nil {
		logs.Error(err)
	} else if fh != nil {
		attachment = fh.Filename
		logs.Info(attachment)
	}

	if len(tid) == 0 {
		if id, err := models.AddTopic(title, category, labels, content); err != nil {
			logs.Error(err)
		} else {
			tid = strconv.FormatInt(id, 10)
		}
	} else {
		if err := models.ModifyTopic(tid, title, category, labels, content, attachment); err != nil {
			logs.Error(err)
		}
	}

	if len(attachment) > 0 {
		attachmentParentDir := path.Join("attachment", tid)
		if !com.IsExist(attachmentParentDir) {
			os.MkdirAll(attachmentParentDir, os.ModePerm)
		}
		if err := this.SaveToFile("attachment", path.Join(attachmentParentDir, attachment)); err != nil {
			logs.Error(err)
		}
	}
	this.Redirect("/topic", 302)
}

func (this *TopicController) Get() {
	this.Data["IsTopic"] = true
	this.TplName = "topic.html"
	this.Data["IsLogin"] = checkAccount(this.Ctx)
	var err error
	if this.Data["Topics"], err = models.GetAllTopics("", "", false); err != nil {
		logs.Error(err)
	}
}
